package com.enniswu.weitter.user.info;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.enniswu.weitter.R;
import com.enniswu.weitter.base.BaseFragment;
import com.enniswu.weitter.browse.BrowseActivity;
import com.enniswu.weitter.data.local.DBSupport;
import com.enniswu.weitter.data.local.SPSupport;
import com.enniswu.weitter.entity.Post;
import com.enniswu.weitter.entity.User;
import com.enniswu.weitter.setting.SettingActivity;
import com.enniswu.weitter.user.start.StartActivity;
import com.enniswu.weitter.user.update.UpdateInfoActivity;
import com.enniswu.weitter.user.userlist.UserListActivity;
import com.enniswu.weitter.widget.adapter.PostAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.BlurTransformation;

public class UserInfoFragment extends BaseFragment<UserInfoContract.Presenter> implements UserInfoContract.View, OnRefreshListener, OnLoadMoreListener {

    @BindView(R.id.iv_background)
    ImageView ivBackground;
    @BindView(R.id.iv_portrait)
    ImageView ivPortrait;
    @BindView(R.id.bt_variety_a)
    Button btVarietyA;
    @BindView(R.id.bt_variety_b)
    Button btVarietyB;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_gender)
    ImageView ivGender;
    @BindView(R.id.tv_following)
    TextView tvFollowing;
    @BindView(R.id.tv_follows)
    TextView tvFollows;
    @BindView(R.id.tv_synopsis)
    TextView tvSynopsis;
    @BindView(R.id.rv_moment)
    RecyclerView rvMoment;
    @BindView(R.id.rl_user)
    SmartRefreshLayout rlUser;
    private List<Post> posts;
    private PostAdapter adapter;
    private User user;
    private boolean isFollowed;
    private List<Integer> following;
    private List<Integer> follows;
    private User current;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            user = getArguments().getParcelable("user");
        }
    }

    public static UserInfoFragment newInstance(@Nullable User user) {
        Bundle bundle = new Bundle();
        bundle.putParcelable("user", user);
        UserInfoFragment fragment = new UserInfoFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int setContentView() {
        return R.layout.fragment_user_info;
    }

    @Override
    protected void onCreateView(View contentView) {
        rlUser.setOnRefreshListener(this);
        rlUser.setOnLoadMoreListener(this);
        current = DBSupport.getInstance().getCurrentUser();
        posts = Collections.synchronizedList(new ArrayList<Post>());
        adapter = new PostAdapter(posts);
        rvMoment.setNestedScrollingEnabled(false);
        rvMoment.setLayoutManager(new LinearLayoutManager(getContext()));
        rvMoment.setAdapter(adapter);
        presenter = new UserInfoPresenter(this, user == null ? 0 : user.getId());
        EventBus.getDefault().register(this);
        setUser();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void setFollowing(List<Integer> following) {
        this.following = following;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvFollowing.setText(String.valueOf(UserInfoFragment.this.following.size()));
            }
        });
    }

    @Override
    public void setFollows(List<Integer> follows) {
        this.follows = follows;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvFollows.setText(String.valueOf(UserInfoFragment.this.follows.size()));
            }
        });
    }

    @Override
    public void setFollow(final boolean isFollowed) {
        this.isFollowed = isFollowed;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isFollowed) {
                    btVarietyB.setText(R.string.info_bt_b_unFollow);
                } else {
                    btVarietyB.setText(R.string.info_bt_b_follow);
                }
            }
        });
    }

    @Override
    public void notifyDataInserted(final int count) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.notifyItemRangeInserted(posts.size() - count, count);
                adapter.notifyItemRangeChanged(posts.size() - count, count);
            }
        });
    }

    @Override
    public void notifyDataSetChanged() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void notifyItemUserChanged(Post post) {
        final int index = posts.indexOf(post);
        if (index < 0)
            return;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.notifyItemChanged(index);
            }
        });
    }

    @Override
    public void addPosts(List<Post> posts) {
        this.posts.addAll(posts);
    }

    @Override
    public void clearPosts() {
        posts.clear();
    }

    @Override
    public void refresh() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                rlUser.autoRefresh();
            }
        });
    }

    @Override
    public void finishLoadData() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                rlUser.finishRefresh();
                rlUser.finishLoadMore();
            }
        });
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        presenter.getPosts(posts.size() + 1);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        presenter.getPosts(1);
        presenter.getUser(user.getId());
    }

    @OnClick({R.id.iv_portrait, R.id.ll_following, R.id.ll_follows})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_portrait:
                if (user == null)
                    return;
                Intent intent = new Intent(getContext(), BrowseActivity.class);
                intent.putExtra("album",
                        (Serializable) Collections.singletonList(user.getPortrait()));
                startActivity(intent);
                break;
            case R.id.ll_following:
                if (following == null)
                    return;
                Intent following = new Intent(getContext(), UserListActivity.class);
                following.putExtra("ids", (Serializable) this.following);
                following.putExtra("title", UserListActivity.TITLE_FOLLOWING);
                startActivity(following);
                break;
            case R.id.ll_follows:
                if (follows == null)
                    return;
                Intent follows = new Intent(getContext(), UserListActivity.class);
                follows.putExtra("ids", (Serializable) this.follows);
                follows.putExtra("title", UserListActivity.TITLE_FOLLOWS);
                startActivity(follows);
                break;
        }
    }

    @Subscribe
    @Override
    public void updateInfo(final User user) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                UserInfoFragment.this.user = user;
                current = DBSupport.getInstance().getCurrentUser();
                setUser();
            }
        });
    }

    private void setUser() {
        if (user == null || user.getId() == 0)
            setNullInfo();
        else
            setUserInfo();
    }

    private void setUserInfo() {
        presenter.setOrientation(user.getId());
        Glide.with(this)
                .load(user.getPortrait())
                .apply(new RequestOptions()
                        .transform(new BlurTransformation()))
                .into(ivBackground);
        Glide.with(this)
                .load(user.getPortrait())
                .apply(new RequestOptions().circleCrop())
                .into(ivPortrait);
        tvName.setText(user.getName());
        tvSynopsis.setText(user.getSynopsis());
        if (user.getGender() == 0)
            ivGender.setImageResource(R.drawable.ic_female);
        else
            ivGender.setImageResource(R.drawable.ic_male);
        rlUser.setEnableRefresh(true);
        rlUser.setEnableLoadMore(true);
        if (user.equals(current) && !TextUtils.isEmpty(SPSupport.getInstance().getSessionId())) {
            btVarietyA.setText(R.string.info_bt_a_update);
            btVarietyB.setText(R.string.info_bt_b_setting);
            btVarietyA.setOnClickListener(toUpdate);
            btVarietyB.setOnClickListener(toSetting);
        } else {
            if (current != null && current.getFollowing() != null &&
                    current.getFollowing().contains(user.getId())) {
                btVarietyB.setText(R.string.info_bt_b_unFollow);
                isFollowed = true;
            } else {
                btVarietyB.setText(R.string.info_bt_b_follow);
                isFollowed = false;
            }
            btVarietyA.setText(R.string.info_bt_a_chat);
            btVarietyA.setOnClickListener(toChat);
            btVarietyB.setOnClickListener(toFollow);
        }
        presenter.getPosts(1);
        presenter.getFollowing();
        presenter.getFollows();
    }

    private void setNullInfo() {
        Glide.with(this)
                .load(R.drawable.ic_portrait_male)
                .apply(new RequestOptions()
                        .transform(new BlurTransformation()))
                .into(ivBackground);
        Glide.with(this)
                .load(R.drawable.ic_portrait_male)
                .apply(new RequestOptions().circleCrop())
                .into(ivPortrait);
        tvName.setText(R.string.not_log);
        tvFollowing.setText(String.valueOf(0));
        tvFollows.setText(String.valueOf(0));
        rlUser.setEnableRefresh(false);
        rlUser.setEnableLoadMore(false);
        btVarietyA.setText(R.string.info_bt_a_start);
        btVarietyB.setText(R.string.info_bt_b_setting);
        btVarietyA.setOnClickListener(toStart);
        btVarietyB.setOnClickListener(toSetting);
        clearPosts();
        notifyDataSetChanged();
    }

    private View.OnClickListener toUpdate = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getContext(), UpdateInfoActivity.class);
            intent.putExtra("user", user);
            startActivity(intent);
        }
    };

    private View.OnClickListener toSetting = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getContext(), SettingActivity.class);
            intent.putExtra("user", user);
            startActivity(intent);
        }
    };

    private View.OnClickListener toStart = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(getContext(), StartActivity.class));
        }
    };

    private View.OnClickListener toChat = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    };

    private View.OnClickListener toFollow = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isFollowed) {
                presenter.unfollow();
            } else {
                presenter.follow();
            }
        }
    };
}
